package com.iw.adoms.entity.editor;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang.StringUtils;

import com.iw.core.orm.hibernate.BaseEntity;

/**   
 * Editor for basic entity which must be inherited from <code>BaseEntity</code>.
 * @author <a href="mailto:rex2.mj@gmail.com">Leo Meng</a>
 * @date $Date: Jan 7, 2013  $
 */
public class EntityPropertyEditor extends PropertyEditorSupport {

	private Class<? extends BaseEntity> clazz;

	public EntityPropertyEditor(Class<? extends BaseEntity> clazz) {
		super();
		this.clazz = clazz;
	}

	@Override
	public void setValue(Object value) {

		if (value != null && value instanceof Integer
				&& !Integer.valueOf(0).equals(value)) {
			try {
				BaseEntity entity = (BaseEntity) clazz.newInstance();
				entity.setId((Integer) value);
				super.setValue(entity);
			} catch (Exception ex) {
				throw new IllegalArgumentException();
			}
		} else {
			super.setValue(value);
		}

	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (!StringUtils.isEmpty(text) && StringUtils.isNumeric(text)) {
			this.setValue(Integer.valueOf(text));
		}else{
			this.setValue(null);
		}
	}

	@Override
	public String getAsText() {
		if (this.getValue() != null
				&& this.getValue() instanceof BaseEntity) {
			return String.valueOf(((BaseEntity) getValue()).getId());
		} else {
			return null;
		}

	}

}